﻿using Business;
using Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WinUI.SearchFrm;

namespace WinUI.Frm_MasterPlan
{
    public partial class Frm_CreateMasterPlan : Form
    {
        #region Variables
        private string messageError;
        //program
        private List<MyProgram> listProgram;
        //projectregion
        private List<Business.Region> listRegion;
        //projectmechanism
        private List<ComboItem> listMech;
        //projectchannel
        private List<ComboItem> listChannel;
        #endregion

        public Frm_CreateMasterPlan(int projectID)
        {
            InitializeComponent();

            this.Text = "Sửa MasterPlan";

            InitTab(projectID);
        }

        public Frm_CreateMasterPlan()
        {
            InitializeComponent();

            InitTab();
        }

        void InitTab(int projectID = -1)
        {
            #region MasterPlan
            //Init list program
            listProgram = new List<MyProgram>();
            //get programs by csid
            Common.ERROR_CODE.ERROR_CODE_ITEMS_SELECT errCodeSelect = Business.Program.GetProgramByCSID(ref messageError, ref listProgram, Global._UserInfo);
            if (errCodeSelect == Common.ERROR_CODE.ERROR_CODE_ITEMS_SELECT.SYSTEM_ERROR)
            {
                MessageBox.Show(messageError);
                this.Close();
                return;
            }
            //set programs combo
            SLK_Program.Properties.DataSource = listProgram;
            SLK_Program.Properties.DisplayMember = "ProgramName";
            SLK_Program.Properties.ValueMember = "ID";

            if (listProgram.Count == 0)
            {
                MessageBox.Show("Không có đề tài được phân công!");
                this.Close();
                return;
            }

            if (projectID == -1)
            {
                SLK_Program.EditValue = listProgram.First().ID;
                //Init MasterPlanCode K00001
                tb_MasterPlanCode.Text = Business.Project.CreateCode();

                //Default Margin K00002
                sE_margin.Value = 50;
            }
            else
            {
                Business.Project.GetProjectByProjectID(ref Global._CurrentProject, projectID);
                SLK_Program.EditValue = Global._CurrentProject.ProgramID;

                tb_MasterPlanName.Text = Global._CurrentProject.ProjectName;
                tb_MasterPlanCode.Text = Global._CurrentProject.ProjectCode;
                sE_margin.Value = (decimal)Global._CurrentProject.DefaultMargin;
                dE_StartDate.DateTime = Global._CurrentProject.StartDate;
                dE_EndDate.DateTime = Global._CurrentProject.EndDate;
            }
            #endregion

            #region ProjectRegion
            //get regions list
            listRegion = new List<Business.Region>();
            errCodeSelect = Business.Region.getRegionForFrm(ref messageError, ref listRegion);
            if (errCodeSelect == Common.ERROR_CODE.ERROR_CODE_ITEMS_SELECT.SYSTEM_ERROR)
            {
                MessageBox.Show(messageError);
                this.Close();
                return;
            }
            //get regions for combo
            List<ComboItem> listRegionsCombo = (from dt in listRegion
                                               where dt.RegionLevel == 4
                                               select new ComboItem(dt.RegionCode, dt.RegionName)).ToList();

            rI_Lookup_PR_Temp_Regions.DataSource = listRegionsCombo;
            rI_Lookup_PR_Temp_Regions.DisplayMember = "Text";
            rI_Lookup_PR_Temp_Regions.ValueMember = "Value";

            if (projectID != -1)
            {
                Business.ProjectRegion.GetProjectRegionByProjectID(ref Global._CurrentProjectRegion, projectID);
                ShowCurrentProjectRegion();
            }
            #endregion

            #region ProjectMechanism
            //Init Mechs
            listMech = new List<ComboItem>();
            //Business.CodeDetail.GetMechanicismForCombo(ref listMech);
            cmbE_Mech_Type.Properties.DataSource = listMech;
            cmbE_Mech_Type.Properties.DisplayMember = "Text";
            cmbE_Mech_Type.Properties.ValueMember = "ID";

            rI_Mechs_Lookup_Mechanicism.DataSource = listMech;
            rI_Mechs_Lookup_Mechanicism.DisplayMember = "Text";
            rI_Mechs_Lookup_Mechanicism.ValueMember = "ID";

            //if (projectID != -1)
            //{
            //    Business.ProjectMechanicism.GetProjectMechanicismByProjectID(ref Global._CurrentProjectMechanicism, projectID);
            //    ShowCurrentProjectMechanicism();
            //}
            #endregion

            #region ProjectChannel
            //Init Channel Tab  
            //init domain

            //init region

            //init mechanicism

            //init channel
            listChannel = new List<ComboItem>();
            //Business.CodeDetail.GetChannelForCombo(ref listChannel);
            cmbE_Channel_Type.Properties.DataSource = listChannel;
            cmbE_Channel_Type.Properties.DisplayMember = "Text";
            cmbE_Channel_Type.Properties.ValueMember = "ID";

            ShowCurrentProjectChannel();
            #endregion
        }

        #region MasterPlan
        // Master Plan K00005
        private int CheckProjectInputData(DateTime startdate, DateTime enddate, string MasterPlanName)
        {
            if (MasterPlanName.Trim().Equals("")
                || startdate.Equals(DateTime.MinValue)
                || enddate.Equals(DateTime.MinValue))
            {
                return 2;
            }
            if (startdate.CompareTo(enddate) >= 0)
            {
                return 1;
            }
            return 0;
        }

        private void bt_Finish_Click(object sender, EventArgs e)
        {
            //check input data
            int checkValue = CheckProjectInputData(dE_StartDate.DateTime, dE_EndDate.DateTime, tb_MasterPlanName.Text);
            switch (checkValue)
            {
                case 1:
                    MessageBox.Show(Common.MESSAGE_STRING.STARTDATE_GREATER_THAN_ENDDATE, Common.MESSAGE_TITLE.ERROR);
                    break;
                case 2:
                    MessageBox.Show(Common.MESSAGE_STRING.NULLTEXT_ERROR, Common.MESSAGE_TITLE.ERROR);
                    break;
                default:
                    //valid data
                    Project pj = new Project();
                    pj.ProgramID = (long)SLK_Program.EditValue;
                    pj.ProjectCode = tb_MasterPlanCode.Text;
                    pj.ProjectName = tb_MasterPlanName.Text;
                    pj.DefaultMargin = (double)sE_margin.Value;
                    pj.StartDate = dE_StartDate.DateTime;
                    pj.EndDate = dE_EndDate.DateTime;

                    if (Global._CurrentProject != null)
                    {
                        //update
                        Common.ERROR_CODE.ERROR_CODE_ITEMS_UPDATE errCode = Business.Project.Update(ref pj, Global._CurrentProject.ID, Global._UserInfo);
                        //show message
                        MessageBox.Show(Common.EnumUtils.stringValueOf(errCode));

                        if (errCode == Common.ERROR_CODE.ERROR_CODE_ITEMS_UPDATE.SUCCESS)
                        {
                            Global._CurrentProject = pj;
                        }
                        break;
                    }
                    else
                    {
                        //add new masterplan
                        Common.ERROR_CODE.ERROR_CODE_ITEMS_ADDNEW errCode = Business.Project.AddNew(ref pj, Global._UserInfo);
                        //show message
                        MessageBox.Show(Common.EnumUtils.stringValueOf(errCode));

                        if (errCode == Common.ERROR_CODE.ERROR_CODE_ITEMS_ADDNEW.SUCCESS)
                        {
                            Global._CurrentProject = pj;
                        }
                        break;
                    }

            }
        }
        #endregion

        #region ProjectRegion
        private void tb_Province_Click(object sender, EventArgs e)
        {
            //show region form
            RegionFrm frm = new RegionFrm(listRegion, this);
            frm.StartPosition = FormStartPosition.CenterScreen;
            frm.ShowDialog();
        }

        // Show Data Checked K00009
        public void ShowCheckedRegions(List<Business.Region> data)
        {
            if (data.Count != 0) tb_Province.Text = "Selected";
            gridRegionTemp.DataSource = data;
        }

        // AddNew ProjectRegion K00011
        private void bt_AddPRegion_Click(object sender, EventArgs e)
        {
            Common.ERROR_CODE.ERROR_CODE_ITEMS_CHECK_DUPPLICATE errCodeDupe;
            //check input data
            string RegionDomain = tb_Domain.Text.Trim();
            if ((!RegionDomain.Equals("") && !tb_Province.Text.Trim().Equals("")))
            {
                errCodeDupe = Business.ProjectRegion.CheckRegionNameExists(ref messageError, RegionDomain, Global._CurrentProject.ID);
                if (errCodeDupe == Common.ERROR_CODE.ERROR_CODE_ITEMS_CHECK_DUPPLICATE.SUCCESS)
                {
                    string _RegsCode = Business.ProjectRegion.CreateCode(Global._CurrentProject.ID);
                    //string _RegsCode = "00001";

                    List<ProjectRegion> newPR = new List<ProjectRegion>();
                    List<Business.Region> data = (List<Business.Region>)gridRegionTemp.DataSource;

                    newPR.Add(new ProjectRegion { ProjectID = Global._CurrentProject.ID, RegionCode = _RegsCode, RegionLevel = 3, RegionName = RegionDomain });

                    if (data.Count > 0)
                    {
                        foreach (var item in data)
                        {
                            ProjectRegion _pr = new ProjectRegion();
                            _pr.ParentCode = _RegsCode;
                            _pr.ProjectID = Global._CurrentProject.ID;
                            _pr.RegionCode = item.RegionCode;
                            _pr.RegionLevel = item.RegionLevel;
                            _pr.RegionName = item.RegionName;

                            newPR.Add(_pr);
                        }
                    }

                    //add new
                    Common.ERROR_CODE.ERROR_CODE_ITEMS_ADDNEW errCode = Business.ProjectRegion.AddNew(ref messageError, ref newPR, ref Global._UserInfo);
                    //show message
                    MessageBox.Show(Common.EnumUtils.stringValueOf(errCode));

                    if (errCode == Common.ERROR_CODE.ERROR_CODE_ITEMS_ADDNEW.SUCCESS)
                    {
                        if (Global._CurrentProjectRegion != null)
                        {
                            Global._CurrentProjectRegion.AddRange(newPR);
                        }
                        else
                        {
                            Global._CurrentProjectRegion = newPR;
                        }

                        ShowCurrentProjectRegion();
                    }
                }
                else
                {
                    MessageBox.Show(messageError);
                }
            }
            else
            {
                MessageBox.Show(Common.MESSAGE_STRING.NULLTEXT_ERROR, Common.MESSAGE_TITLE.ERROR);
            }
        }

        private void ShowCurrentProjectRegion()
        {
            var domaindata = (from d in Global._CurrentProjectRegion
                             where d.RegionLevel == 3
                             select new ComboItem(d.RegionCode, d.RegionName)).ToList();

            var regiondata = (from r in Global._CurrentProjectRegion
                             where r.RegionLevel == 4
                             select new ComboItem(r.ID, r.RegionName)).ToList();

            rI_Lookup_PR_Main_Domains.DataSource = domaindata;
            rI_Lookup_PR_Main_Domains.DisplayMember = "Text";
            rI_Lookup_PR_Main_Domains.ValueMember = "Value";

            rI_Lookup_PR_Main_Regions.DataSource = regiondata;
            rI_Lookup_PR_Main_Regions.DisplayMember = "Text";
            rI_Lookup_PR_Main_Regions.ValueMember = "ID";

            gridRegionAdded.DataSource = Global._CurrentProjectRegion.Where(p => p.RegionLevel == 4).ToList();
        }

        // TextChanged Event K00010
        private void txtRegionDomain_TextChanged(object sender, EventArgs e)
        {
            if (!tb_Domain.Text.Trim().Equals(""))
            {
                lblRegion.Text = "Tên miền: " + tb_Domain.Text.Trim();
            }
        }

        private void rI_btn_PR_Temp_Actions_ButtonPressed(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            gridViewPRTemp.DeleteRow(gridViewPRTemp.FocusedRowHandle);
        }

        private void rI_btn_PR_Main_Actions_ButtonPressed(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            DialogResult dr = MessageBox.Show(Common.MESSAGE_STRING.CONFIRM_SELECT, Common.MESSAGE_TITLE.CONFIRM, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dr == System.Windows.Forms.DialogResult.Yes)
            {
                int cellValue = Convert.ToInt32(gridViewPRMain.GetRowCellValue(gridViewPRMain.FocusedRowHandle, "ID").ToString());
                Common.ERROR_CODE.ERROR_CODE_ITEMS_UPDATE errCode = Business.ProjectRegion.DisableProjectRegion(ref messageError, ref Global._CurrentProjectRegion, cellValue, Global._UserInfo);
                if (errCode == Common.ERROR_CODE.ERROR_CODE_ITEMS_UPDATE.SUCCESS)
                {
                        gridRegionAdded.DataSource = Global._CurrentProjectRegion;
                }
            }
        }
        #endregion

        #region ProjectMechanicism
        private void rI_Button_Mechs_Actions_ButtonPressed(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
        //    int cellValue = Convert.ToInt32(gridMechaView.GetRowCellValue(gridMechaView.FocusedRowHandle, "ID").ToString());
        //    DialogResult dr = MessageBox.Show(Common.MESSAGE_STRING.CONFIRM_SELECT, Common.MESSAGE_TITLE.CONFIRM, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        //    if (dr == System.Windows.Forms.DialogResult.Yes)
        //    {
        //        int row = gridMechaView.FocusedRowHandle;
        //        //Common.ERROR_CODE.ERROR_CODE_ITEMS_UPDATE errCode = Business.ProjectMechanicism.DisableProjectMechanicism(ref messageError, ref Global._CurrentProjectMechanicism, cellValue, Global._UserInfo);
        //        if (errCode == Common.ERROR_CODE.ERROR_CODE_ITEMS_UPDATE.SUCCESS)
        //        {
        //            //gridMech.DataSource = Global._CurrentProjectMechanicism;
        //        }
        //    }
        }

        private void cmbE_Regions_Enter(object sender, EventArgs e)
        {
            if (Global._CurrentProjectRegion.Count != 0)
            {
                cmbE_Mech_Domain.Properties.DataSource = (from p in Global._CurrentProjectRegion
                                                         where p.RegionLevel == 3
                                                         select new ComboItem(p.RegionCode, p.RegionName)).ToList();
                cmbE_Mech_Domain.Properties.DisplayMember = "Text";
                cmbE_Mech_Domain.Properties.ValueMember = "Value";
            }
            else
            {
                MessageBox.Show(messageError);
            }
        }

        private void ShowCurrentProjectMechanicism()
        {
            var regiondata = (from r in Global._CurrentProjectRegion
                              where r.RegionLevel == 4
                              select new ComboItem(r.ID, r.RegionName)).ToList();
            rI_Mechs_Lookup_Region.DataSource = regiondata;
            rI_Mechs_Lookup_Region.DisplayMember = "Text";
            rI_Mechs_Lookup_Region.ValueMember = "ID";

            gridMech.DataSource = Global._CurrentProjectMechanicism;
        }

        // Project Mechanicism AddNew
        private void bt_AddNewMech_Click(object sender, EventArgs e)
        {
            //if (!(cmbE_Mech_Domain.Text.Equals("") || cmbE_Mech_Type.Text.Equals("")))
            //{
            //    List<MyProjectMechanicism> listMPM = new List<MyProjectMechanicism>();
            //    foreach (DevExpress.XtraEditors.Controls.CheckedListBoxItem item in cmbE_Mech_Type.Properties.Items)
            //    {
            //        if (item.CheckState == CheckState.Checked)
            //        {
            //            foreach (DevExpress.XtraEditors.Controls.CheckedListBoxItem data in cmbE_Mech_Domain.Properties.Items)
            //            {
            //                if (data.CheckState == CheckState.Checked)
            //                {
            //                    foreach (var val in Global._CurrentProjectRegion.Where(p => p.ParentCode == data.Value.ToString()))
            //                    {
            //                        MyProjectMechanicism pm = new MyProjectMechanicism();
            //                        pm.ProjectID = Global._CurrentProject.ID;
            //                        pm.ProjectRegion = val.ID;
            //                        pm.Mechanicism = Convert.ToInt32(item.Value.ToString());

            //                        listMPM.Add(pm);
            //                    }
            //                }
            //            }
            //        }
            //    }

                //if (Global._CurrentProjectMechanicism != null)
                //{
                //    listMPM = listMPM.Except(Global._CurrentProjectMechanicism).ToList();
                //}

                //add new
                //Common.ERROR_CODE.ERROR_CODE_ITEMS_ADDNEW errCode = Business.ProjectMechanicism.AddNew(ref messageError, ref listMPM, ref Global._UserInfo);
                //show message
                //MessageBox.Show(Common.EnumUtils.stringValueOf(errCode));

                //if (errCode == Common.ERROR_CODE.ERROR_CODE_ITEMS_ADDNEW.SUCCESS)
                //{
                //    if (Global._CurrentProjectMechanicism != null)
                //    {
                //        Global._CurrentProjectMechanicism.AddRange(listMPM);
                //    }
                //    else
                //    {
                //        Global._CurrentProjectMechanicism = listMPM;
                //    }

                //    ShowCurrentProjectMechanicism();
                //}
            //}
            //else
            //{
            //    MessageBox.Show(Common.MESSAGE_STRING.NULLTEXT_ERROR, Common.MESSAGE_TITLE.ERROR);
            //}
        }
        #endregion

        #region ProjectChannel
        private void ShowCurrentProjectChannel()
        {
            var domaindata = (from d in Global._CurrentProjectRegion
                              where d.RegionLevel == 3
                              select new ComboItem(d.RegionCode, d.RegionName)).ToList();

            var regiondata = (from r in Global._CurrentProjectRegion
                              where r.RegionLevel == 4
                              select new ComboItem(r.ID, r.RegionName)).ToList();

            rI_islu_Domain.DataSource = domaindata;
            rI_islu_Domain.DisplayMember = "Text";
            rI_islu_Domain.ValueMember = "Value";

            rI_islu_Region.DataSource = regiondata;
            rI_islu_Region.DisplayMember = "Text";
            rI_islu_Region.ValueMember = "ID";

            rI_islu_Mech.DataSource = listMech;
            rI_islu_Mech.DisplayMember = "Text";
            rI_islu_Mech.ValueMember = "ID";

            gridControlChannel.DataSource = Global._CurrentProjectMechanicism;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            //check input data
            //add project channel
            //if success
            //get project channel
            //set data to gridview main
            //show message
        }

        //domain
        private void cmbE_Channel_Domain_Enter(object sender, EventArgs e)
        {

        }

        private void cmbE_Channel_Domain_EditValueChanged(object sender, EventArgs e)
        {

        }
        //end domain

        private void cmbE_Channel_Region_Enter(object sender, EventArgs e)
        {

        }

        private void cmbE_Channel_Mech_Enter(object sender, EventArgs e)
        {

        }

        private void cmbE_Channel_Type_Enter(object sender, EventArgs e)
        {

        }
        #endregion

        private void gridControlChannel_KeyPress(object sender, KeyPressEventArgs e)
        {

        }

        private void gridChannel_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F2)
            {
                ChannelFrm frm = new ChannelFrm(listChannel, this);
                frm.StartPosition = FormStartPosition.CenterScreen;
                frm.ShowDialog();
            }
        }
    }
}
